var displayLang;
var user;
var old_id;
var ds_id;
var ds_type;
var gid;
var ov_id;


$(document).ready(function(){
	displayLang = $("#display-lang").val();
	user = $("#user").val();
	old_id = $("#old_id").val();
	ds_id = $("#ds_id").val();
	ds_type = $("#ds_type").val();
	gid = $("#gid").val();
	ov_id = $("#ov_id").val();
	if($("#tr_id").val() == ""){
		initializeNew(old_id);
	}else{
		initialize($("#tr_id").val(),old_id);
	}
	
	$("#relName").change(function(){
		if(isEmpty($(this))){
			$("#rel_title").text($("span#rel_name").text());
			$("#rel_title").addClass("original");
			$("#rel_title").removeClass("highlight");//========add css
    		$("#relName").parent().find(".originTitle").parent().append(span);
		}else{
			$("#rel_title").text($("#relName").val());
			$("#rel_title").removeClass("original");
			$("#rel_title").addClass("highlight");//========add css
			$("#relName").parent().find(".originTitle").parent().find(".error").remove();
		}
	});
	$(".roleName").change(function(){
		var th = "th[v='"+$(this).attr("id")+"']";
		if(isEmpty($(this))){
			var old = "span[v='"+$(this).attr("id")+"']";
			$(th).text($(old).text());
			$(th).removeClass("highlight");//========add css
			$(th).addClass("original");
    		$(this).parent().find(".originTitle").parent().append(span);
		}else{
			$(th).text($(this).val());
			$(th).removeClass("original");
			$(th).addClass("highlight");//========add css

			$(this).parent().find(".originTitle").parent().find(".error").remove();
		}
	});
	$(".edit-save .cbutton").click(function(){
		window.close();
	});
	$(".edit-save .sbutton").click(function(){
		//check if any of data item  has error msg
		if($(".error").length>0)
			return false;
		//check if the view name is empty
		if(isEmpty($("#relName"))){
			var span = $("<span class='error'></span>");
    		if(displayLang=="en"){
    			span.text("Please enter relation name");
    		}else if(displayLang=="zh"){
    			span.text("请输入关系名称");
    		}
    		$("#relName").parent().find(".originTitle").parent().append(span);
			return false;
		}
		//check if any of data item names is empty
		var flag = false;
		$(".roleName").each(function(){
			if(isEmpty($(this))){
				flag = true;
				var span = $("<span class='error'></span>");
	    		if(displayLang=="en"){
	    			span.text("Please enter role name");
	    		}else if(displayLang=="zh"){
	    			span.text("请输入角色名");
	    		}
	    		$(this).parent().find(".originTitle").parent().append(span);
				return;
			}
		});
		if(flag)
			return false;
		

		var relName =$("#relName").val().trim();
		var new_id = $("#tr_id").val();
		//check if the view name has conflict
		var originTitleSpan = $(".nameBox .originTitle");
//		alert(relName+"|"+gid+"|"+new_id);
        var status = checkRelNameConflict(originTitleSpan,relName,gid,new_id);
        if(status==0)
        	return false;
        else if(status==2){
        	var title ;
        	var msg;
        	if(displayLang=="en"){
        		title="Operating tips";
        		msg = "The view of the name has existed and can be overwritten. Do you want to overwrite it?";
        	}else if(displayLang=="zh"){
        		title="操作提示";
        		msg = "该名称的视图已存在，可以进行覆盖。 您要覆盖它吗?";
        	}
        	$.messager.confirm(title, msg, function (data) {
        		if (data) {
        			save(relName) ;
        			var location = getEntityLinkHref(genre,eid);
            		if(displayLang=="zh")
            			location = location+"&lang=zh";
            		window.location = location;
        		}
        	});
        }else{
        	var sels = new Array();
        	$(".roleName").each(function(){
        		var v = $(this).attr("id");
        		var a = $(this).val();
        		var item = new Object();
        		item["v"] = v;
        		item["role"] = a;
        		sels.push(item);
//        		alert("item:"+item["v"]+"|"+item["role"]);
        	});
        	var tr_id = $("#tr_id").val();
            save(tr_id, sels, relName, user);
        }
	});
});
function isEmpty(input){
	if($(input).val().trim()=="")
		return true;
	return false;
}
function checkRoles(sels) {
	if (sels.length == 0)
		return false;
	var ret = true;
	for ( var i=0; i<sels.length; i++) {
		var role = sels[i]["role"];
		role = role.trim();
		if (role == "") {
			ret = false;
		}
	}
	return ret;
}
function initializeNew(old_id) {
	var data = {};
	data["old_id"] = old_id+"";
	data["slang"] = $("#display-lang").val();
	data["olang"] = $("#objLang option:selected").val();
	data = JSON.stringify(data);
	data = ("translateNew=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationIntoSession",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var new_id = result["new_id"];
			$("#tr_id").val(new_id);
			getRelationMeta(old_id);
			getRelationResult(old_id, ds_type, ds_id);
		}
	});
}
function initialize(relation_id, old_id) {
	var data = {};
	data["new_id"] = relation_id;
	data["old_id"] = old_id;
	data["olang"] = $("#objLang option:selected").val();
	data = JSON.stringify(data);
	data = ("translateGet=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationIntoSession",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var new_id = result["new_id"];
			var rel_id = new_id;
			if(new_id == 0){
				rel_id = old_id;
			}
			getRelationMeta(rel_id);
			getRelationResult(rel_id, ds_type, ds_id);
			/*if(!isEmpty($("#relName"))){
				$("#rel_title").text($("#relName").val());
				$(th).removeClass("original");
				$("#rel_title").addClass("highlight");//========add css
			}
			$(".roleName").each(function(){
				if(!isEmpty($(this))){
					var th = "th[v='"+$(this).attr("id")+"']";
					$(th).text($(this).val());
					$(th).removeClass("original");
					$(th).addClass("highlight");//========add css
				}
			});*/
		}
	});
}

function save(relation_id, sels, name, user){
	var flag = false;
	var data = {};
	data["id"] = relation_id;
	data["roles"] = sels;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/changeRoles",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var data = {};
			data["id"] = relation_id;
			data["name"] = name;
			data["user"] = user;
			data["gid"] = $("#gid").val();
			data = JSON.stringify(data);
			data = ("data=" + encodeURIComponent(data));
			$.ajax({
				url : "/sview/saveRelation",
				async : true,
				data : data,
				dataType : "json",
				type : "post",
				success : function(result) {
					var rs = result["result"];
					if(rs=="OK"){
						var tr_id = result["rel_id"];
						$("#tr_id").val(tr_id);
//						alert("id:"+$("#tr_id").val());
						if(displayLang == 'en'){
							alert("Saved!");
						}else if(displayLang == 'zh'){
							alert("已保存。");
						}
//						if (tr_id != 0) {
//							window.location.reload();
//						} else {
//							window.close();
//						}
						return true;
//						{
//			            	window.location.reload();
//			            	var genre = $("#ds_type").val()=="custom"?"c":"u";
//			        		var location = "/sview/dataset/"+genre+$("#ds_id").val();
//			        		
//			        		alert(location);
////			        		if(displayLang=="zh")
////			        			location = location+"&lang=zh";
////			        		window.location = location;
//			            } 
						
					}else if(rs == "nogid"){
						if(displayLang == 'en'){
							alert("Failed! group id param missing!");
						}else if(displayLang == 'zh'){
							alert("操作失败: 未确定编辑组。");
						}
						flag = false;
					}else if(rs == "nosession"){
						if(displayLang == 'en'){
							alert("Failed! Session has timed out!Please refresh the page.")
						}else if(displayLang == 'zh'){
							alert("操作失败: 会话已过期，请刷新页面。");
						}
						flag = false;
					}
				}
			});
		}
	});
	return flag;
}

function checkRelNameConflict(originTitleSpan,relName,gid,rel_id){
	var flag = 1 ;
	var data={};
	data["name"] = relName;
	data["groupID"] = $("#gid").val();
	data["rel_id"] = rel_id+"";
    data =  JSON.stringify(data);
    data ="checkRelNameConflict="+encodeURIComponent(data);
    $.ajax({
    	url:"/sview/relationInfo",
     	async:false,
     	data:data,
     	dataType:"text",
     	type:"post",
        success:function(result){
        	if(result=="conflict"){
        		var span = $("<span class='error'></span>");
        		if(displayLang=="en"){
        			span.text("The name has existed");
        		}else if(displayLang=="zh"){
        			span.text("名称已经存在");
        		}
        		originTitleSpan.parent().append(span);
        		flag = 0;
        	}else if(result=="ask"){
                flag = 2;
        	}
         }
    });
    return flag;
}

function getRelationMeta(id) {
	var data = {};
	data["id"] = id+"";
	data["user"] = $("#user").val();
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationInfo",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var name = result["name"];
//			var user = result["user"];
			var group = result["group"];
			var date = result["date"];
			var canedit = result["canedit"];
			$("#rel_title").text(name);
			if(displayLang == 'en'){
				$("#rel_meta").html("group: " + group + "<br />" + "Date: " + date);
			}else if(displayLang == 'zh'){
				$("#rel_meta").html("编辑组: " + group + "<br />" + "创建日期: " + date);
			}
		}
	});
}

function getRelationResult(id, ds_type, ds_id) {
	var data = {};
	data["id"] = id+"";
	data["ds_type"] = ds_type;
	data["ds_id"] = ds_id;
	data["new"] = "new";
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$("#onloading").dialog("open");
	$.ajax({
		url : "/sview/relationResult",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			$("#onloading").dialog("close");
			var table = $("<table></table>");
			$("#rel_table").html(table);
			var array = result["result"];
			var tableTitle = array[0];
			var trhead = $("<tr></tr>");
			table.append(trhead);
			for ( var i = 0; i < tableTitle.length; i++) {
				var column = tableTitle[i];
				var v = column["v"];
				var vname = column["vname"];
				var th = $("<th class='original'></th>");
				th.attr("v", v);
				th.text(vname);
				trhead.append(th);
			}
			for ( var i = 1; i < array.length; i++) {
				var trbody = $("<tr></tr>");
				table.append(trbody);
				var item = array[i];
				for ( var j = 0; j < item.length; j++) {
					var ele = item[j];
					var v = ele["v"];
					var name = new String(ele["name"]);
					var content = ele["content"];
					var dis = ele["displayName"];//content;
//					if (name.indexOf("u") == 0) {
//						dis = getLocalname(content);
//					}
					var td = $("<td></td>");
					trbody.append(td);
					td.attr("v", v);
					td.attr("name", name);
					var div = $("<span></span>");
					div.attr("title", content);
					div.text(dis);
					td.append(div);
				}
			}
		}
	});
}